package com.tumblr.anond2.solr.client.solrj;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.HashMap;
import java.util.Map;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer.RemoteSolrException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Solr client for Realtime Get.
 * <p>put, get, remove.</p>
 */
public class SolrKVSClient {

	final static Logger logger = LoggerFactory.getLogger(SolrKVSClient.class);
	
	private static SolrKVSClient instance = new SolrKVSClient();
	private static SolrServer server = null;
	
	private SolrKVSClient() {
	}
	
	public static SolrKVSClient getInstance() throws Exception {
		server = checkNotNull(SolrConnection.getSolrServer(), "server not found");
		return instance;
	}
	
	public String get(String key) throws Exception{
		SolrDocument doc = this.getDoc(key);
		if (doc == null){
			return null;
		}
		return (String) doc.get("f1_s");
	}
	
	public SolrDocument getDoc(String key) throws Exception{
		ModifiableSolrParams params = new ModifiableSolrParams();
		params.add("qt", "/get");
		params.add("id", key);
		QueryResponse response = server.query(params);
		return (SolrDocument) response.getResponse().get("doc");
	}

	public void put(String key, String value) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("f1_s", value);
		this.putDoc(key, map, null);
	}
	
	public boolean putDoc(String key, Map<String, Object> values, Object version) throws Exception{
		SolrInputDocument doc = new SolrInputDocument();
		doc.addField("id", key);
		if (version != null) doc.addField("_version_", Long.parseLong(version.toString()));
		for (String value : values.keySet()){
			doc.addField(value, values.get(value));
		}
		try{
			server.add(doc);
		} catch (RemoteSolrException e) {
			//logger.error(e.getMessage(), e);
			return false;
		}
		return true;
	}
	
	public void remove(String key) throws Exception{
		server.deleteById(key);
	}

}
